package com.apexsoft.test;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.MybatisConfiguration;
import com.baomidou.mybatisplus.entity.GlobalConfiguration;
import com.baomidou.mybatisplus.enums.DBType;
import com.baomidou.mybatisplus.mapper.AutoSqlInjector;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

/**
 * ESB控制台数据源
 *
 * @author lowezheng
 * Date: 2019-07-30
 * @version 1.0.0
 * @since jdk1.8
 */
@Component("esbconsole")
@Configuration
@ConfigurationProperties(prefix = "spring.datasource.esbconsole")
@MapperScan(basePackages = "com.apexsoft.common.mapper.esbconsole", sqlSessionTemplateRef = "esbconsoleSqlSessionTemplate")
public class EsbConsoleConfigDatasourceConfig extends DruidDataSource {


    @Bean(name = "esbconsoleSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("esbconsole") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(dataSource);

        //mybatis配置
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setMapUnderscoreToCamelCase(true);
        bean.setConfiguration(configuration);

        //mybatis-plus配置
        GlobalConfiguration globalConfig = new GlobalConfiguration();
        globalConfig.setDbColumnUnderline(true);
        globalConfig.setSqlInjector(new AutoSqlInjector());
        bean.setGlobalConfig(globalConfig);
        bean.setPlugins(new Interceptor[]{new PaginationInterceptor().setDialectType(DBType.MYSQL.getDb())});
        bean.setMapperLocations((new PathMatchingResourcePatternResolver()).getResources("classpath*:mybatis/esbConsole/*.xml"));

        return bean.getObject();
    }

    @Bean(name = "esbconsoleSqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("esbconsoleSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean(name = "esbconsoleTransactionManger")
    public DataSourceTransactionManager dataSourceTransactionManager(@Qualifier("esbconsole") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

}
